package com.jxc.jxcmanage.config;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StopWatch;
import com.jxc.jxcmanage.annotation.Api;
import com.jxc.jxcmanage.common.ResultBean;
import com.jxc.jxcmanage.dto.BaseDto;

import java.lang.reflect.Method;

/**
 * 接口AOP拦截器
 * 
 * @author Jeremy Xiong
 * 2018-11-08 09:28
 */
@Aspect
@Component
@Scope("prototype")
public class WebInterceptor {
	private static Logger LOGGER = LoggerFactory.getLogger(WebInterceptor.class);

	@Around("@annotation(com.jxc.jxcmanage.annotation.Api) || @within(com.jxc.jxcmanage.annotation.Api)")
	public Object intercept(ProceedingJoinPoint pjp) {
		StopWatch sw = new StopWatch();
		sw.start();
		boolean exclude = false;
		Method method = ((MethodSignature) pjp.getSignature()).getMethod();
		LOGGER.info("..........{}..........", method);
		Api onMethod = AnnotationUtils.getAnnotation(method, Api.class);
		LOGGER.info("..........{}..........", onMethod);
		if (onMethod != null) {
			exclude = onMethod.exclude();
		}
		Api onType = AnnotationUtils.findAnnotation(pjp.getTarget().getClass(), Api.class);
		Object[] args = pjp.getArgs();
		BaseDto baseDto = new BaseDto();
		if (args.length == 1) {
			if (args[0] instanceof BaseDto) {
				baseDto = (BaseDto) args[0];
			}
		}
		if (onType != null) {
			if (onMethod == null) {
				exclude = onType.exclude();
			}
		} else {
			if (ObjectUtils.isEmpty(baseDto.getUserId()) || StringUtils.isEmpty(baseDto.getUserCode())) {
				return ResultBean.fail("请首先登录！");
			}
		}
		sw.stop();
		return ResultBean.success();
	}
}
